<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            /*
            1 2 4 5 4 3 2 1
            思路：从后往前，找到一个比后面一位小的数

            */
            var nextPermutation = function (nums) {
                let index = -1
                for (let i = nums.length - 2; i >= 0; i--) {
                    if (nums[i] < nums[i + 1]) {
                        index = i
                        break
                    }
                }

                if (index == -1) {
                    nums.sort((a, b) => a - b)
                    return nums
                }
                //找到之后，还需要比较大小
                for (let i = nums.length - 1; i > index; i--) {
                    if (nums[i] > nums[index]) {
                        ;[nums[i], nums[index]] = [nums[index], nums[i]]
                        break
                    }
                }
                //接下来在排序,因为替换以后，可以确定右侧是递减序列
                let left = index + 1
                let right = nums.length - 1
                while (left < right) {
                    ;[nums[left], nums[right]] = [nums[right], nums[left]]
                    left++
                    right--
                }
                return nums
            }
            console.log(nextPermutation([1, 2, 3]))
        </script>
    </body>
</html>
